import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from 'element-plus'
import {
  supplierListApi,
  supplierStoreApi,
  supplierUpdateApi,
  supplierDeleteApi,
  supplierShowApi,
} from "@/api/quotedPriceApi";
import {
  productListApi
} from "@/api/purchaseOrderApi";
export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 20,
    keyword: null,
    status: null,

  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "supplierId",
      width: 60
    },
    {
      label: "供应商名称",
      prop: "supplierName",
      minWidth: 140
    },
    {
      label: "供应商编码",
      prop: "supplierCode",
      minWidth: 120
    },
    {
      label: "联系人姓名",
      prop: "contactName",
      formatter:(row: any)=> {
        return row.contactName ?? '--'
      },
      minWidth: 120
    },
    {
      label: "联系电话",
      prop: "contactPhone",
      formatter:(row: any)=> {
        return row.contactPhone ?? '--'
      },
      minWidth: 120
    },
    {
      label: "联系邮箱",
      prop: "contactEmail",
      formatter:(row: any)=> {
        return row.contactEmail ?? '--'
      },
      minWidth: 120
    },
    {
      label: "状态",
      prop: "status",
      slot: "status",
      minWidth: 100
    },
    {
      label: "地址",
      prop: "address",
      formatter:(row: any)=> {
        return row.address ?? '--'
      },
      minWidth: 180
    },
    {
      label: "创建时间",
      prop: "createdAt",
      minWidth: 160
    },

    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 140
    }
  ];

  function handleSizeChange(val: number) {
    form.page = 1;
    form.perPage = val;
    onSearch()
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    onSearch()
  }

  async function onSearch() {
    loading.value = true;
    const res: any = await supplierListApi(toRaw(form));
    dataList.value = res?.result?.list;
    pagination.total = res?.result?.total;
    pagination.pageSize = res?.result?.perPage*1;
    // pagination.currentPage = res?.result?.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.page = 1;
    form.keyword = null;
    form.status = null;
    formEl.resetFields();
    onSearch();
  };
  // 删除参数为空的键值
  function cleanEmptyData(obj: object) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === null || obj[key] === '') {
        delete obj[key];
      }
    });
    return obj
  }
  async function openDialog(title = "创建供应商", row?: FormItemProps) {

    let formInline = {
      title: title,
      supplierId: row?.supplierId ?? null,
      supplierName: row?.supplierName ?? null,
      supplierCode: row?.supplierCode ?? null,
      contactName: row?.contactName ?? null,
      contactPhone: row?.contactPhone ?? null,
      contactEmail: row?.contactEmail ?? null,
      address: row?.address ?? null,
      status: row?.status ?? 1,
    };
    if (`${title}` === "创建供应商") {

    } else {

    }

    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      top: '5%',
      width: "500px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            let params = {
              supplierName: curData.supplierName,
              supplierCode: curData.supplierCode,
              contactName: curData.contactName,
              contactPhone: curData.contactPhone,
              contactEmail: curData.contactEmail,
              address: curData.address,
              supplierId: curData.supplierId,
              status: curData.status,
            }
            if (title === "创建供应商") {
              supplierStoreApi(cleanEmptyData(params)).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            } else {
              supplierUpdateApi(cleanEmptyData(params)).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();

  });

  function handleDelete(row) {
    ElMessageBox.confirm('确定继续进行删除操作?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      supplierDeleteApi({ supplierId: row.supplierId }).then((res: any) => {
        if(res?.code === 200) {
          message(`删除成功`, { type: "success" });
          onSearch();
        }
      });
    })
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
  };
}
